import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Select, InputNumber, Upload, message, Radio, Space } from 'antd';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import usePromotionsStore from '../../store/promotions/usePromotionsStore';

const { TextArea } = Input;
const { Option } = Select;

const PromotionDetail = ({ visible, onClose, promotion }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState('');
  const [imageLoading, setImageLoading] = useState(false);
  const [linkType, setLinkType] = useState('internal');
  
  const { createPromotion, updatePromotion } = usePromotionsStore();

  useEffect(() => {
    if (visible) {
      if (promotion) {
        form.setFieldsValue({
          ...promotion,
          linkType: promotion.linkType || 'internal',
        });
        setImageUrl(promotion.image || '');
        setLinkType(promotion.linkType || 'internal');
      } else {
        form.resetFields();
        setImageUrl('');
        setLinkType('internal');
        form.setFieldsValue({
          status: 'active',
          weight: 50,
          type: 'banner',
          linkType: 'internal',
        });
      }
    }
  }, [visible, promotion, form]);

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      const submitData = {
        ...values,
        image: imageUrl,
      };

      if (promotion) {
        await updatePromotion(promotion.id, submitData);
        message.success('更新成功');
      } else {
        await createPromotion(submitData);
        message.success('添加成功');
      }
      
      onClose();
    } catch (error) {
      console.error('提交失败:', error);
      message.error('操作失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const uploadButton = (
    <div>
      {imageLoading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传图片</div>
    </div>
  );

  const handleImageChange = (info) => {
    if (info.file.status === 'uploading') {
      setImageLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // 实际项目中这里应该是上传后返回的图片URL
      const url = URL.createObjectURL(info.file.originFileObj);
      setImageUrl(url);
      setImageLoading(false);
      message.success('图片上传成功');
    }
  };

  const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传 JPG/PNG 格式的图片!');
      return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过 2MB!');
      return false;
    }
    return true;
  };

  // 自定义上传处理
  const customUpload = ({ file, onSuccess }) => {
    setTimeout(() => {
      onSuccess('ok');
    }, 0);
  };

  const generateSlug = (name) => {
    return name
      .toLowerCase()
      .replace(/[\u4e00-\u9fa5]/g, '') // 移除中文字符
      .replace(/[^a-z0-9]+/g, '-') // 替换非字母数字为连字符
      .replace(/^-+|-+$/g, '') // 移除开头和结尾的连字符
      .slice(0, 50); // 限制长度
  };

  const handleNameChange = (e) => {
    const name = e.target.value;
    if (!promotion && name) {
      const slug = generateSlug(name);
      form.setFieldValue('slug', slug);
    }
  };

  return (
    <Modal
      title={promotion ? '编辑推广' : '新增推广'}
      open={visible}
      onOk={handleSubmit}
      onCancel={onClose}
      width={800}
      confirmLoading={loading}
      okText="确定"
      cancelText="取消"
    >
      <Form
        form={form}
        layout="vertical"
        style={{ marginTop: 20 }}
      >
        <Form.Item
          name="name"
          label="推广名称"
          rules={[{ required: true, message: '请输入推广名称' }]}
        >
          <Input 
            placeholder="请输入推广名称" 
            maxLength={100}
            onChange={handleNameChange}
          />
        </Form.Item>

        <Form.Item
          name="slug"
          label="Slug"
          rules={[
            { required: true, message: '请输入Slug' },
            { pattern: /^[a-z0-9-]+$/, message: 'Slug只能包含小写字母、数字和连字符' }
          ]}
        >
          <Input placeholder="例如: summer-sale-2024" maxLength={100} />
        </Form.Item>

        <Form.Item
          name="description"
          label="推广描述"
          rules={[{ required: true, message: '请输入推广描述' }]}
        >
          <TextArea
            placeholder="请输入推广描述"
            rows={3}
            maxLength={500}
            showCount
          />
        </Form.Item>

        <Form.Item
          name="type"
          label="推广类型"
          rules={[{ required: true, message: '请选择推广类型' }]}
        >
          <Select placeholder="请选择推广类型">
            <Option value="banner">Banner</Option>
            <Option value="splash">Splash</Option>
          </Select>
        </Form.Item>

        <Form.Item
          label="推广图片"
          required
          help="建议尺寸：Banner 750x400px，Splash 750x1334px"
          style={{ marginBottom: 24 }}
        >
          <Upload
            name="image"
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            customRequest={customUpload}
            beforeUpload={beforeUpload}
            onChange={handleImageChange}
          >
            {imageUrl ? (
              <img 
                src={imageUrl} 
                alt="推广图片" 
                style={{ width: '100%', height: '100%', objectFit: 'cover' }}
              />
            ) : (
              uploadButton
            )}
          </Upload>
        </Form.Item>

        <Form.Item
          name="linkType"
          label="链接类型"
          rules={[{ required: true, message: '请选择链接类型' }]}
        >
          <Radio.Group onChange={(e) => setLinkType(e.target.value)}>
            <Radio value="internal">内链（小程序页面）</Radio>
            <Radio value="external">外链（网页链接）</Radio>
          </Radio.Group>
        </Form.Item>

        <Form.Item
          name="linkUrl"
          label="跳转链接"
          rules={[
            { required: true, message: '请输入跳转链接' },
            linkType === 'external' && { type: 'url', message: '请输入有效的URL' }
          ].filter(Boolean)}
        >
          <Input 
            placeholder={
              linkType === 'internal' 
                ? '例如: /pages/product/detail?id=123' 
                : '例如: https://www.example.com'
            }
          />
        </Form.Item>

        <Space style={{ width: '100%' }} size={16}>
          <Form.Item
            name="weight"
            label="显示权重"
            rules={[{ required: true, message: '请输入权重' }]}
            style={{ flex: 1 }}
          >
            <InputNumber
              min={0}
              max={999}
              placeholder="数值越大越靠前"
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
            style={{ flex: 1 }}
          >
            <Select placeholder="请选择状态">
              <Option value="active">上线</Option>
              <Option value="inactive">下线</Option>
            </Select>
          </Form.Item>
        </Space>
      </Form>
    </Modal>
  );
};

export default PromotionDetail;